package mo.offer_special;

import mo.common.ListNode;

public class L027 {

    public boolean isPalindrome(ListNode head) {
        if (head == null) {
            return true;
        }
        ListNode endOfFirstHalf = endOfFirstHalf(head);
        ListNode secondHalfStart = reverseSecondHalf(endOfFirstHalf.next);

        while (secondHalfStart != null) {
            if (head.val != secondHalfStart.val) {
                return false;
            }
            head = head.next;
            secondHalfStart = secondHalfStart.next;
        }
        return true;
    }

    private ListNode endOfFirstHalf(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

    private ListNode reverseSecondHalf(ListNode root) {
        ListNode prev = null;
        ListNode curr = root;
        while (curr != null) {
            ListNode tmp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = tmp;
        }
        return prev;
    }

}
